import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
// import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NewUser } from './entities/user.entity.new';
import ErrorExcption from 'src/error/ErrorExcption';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(NewUser)
    private userRepository: Repository<NewUser>,
  ) {}

  async create(createUserDto: CreateUserDto) {
    const { username, password, email } = createUserDto;

    const res = await this.userRepository.findOne({
      where: { username: username },
    });

    if (res) {
      throw new ErrorExcption('用户名重复', 400);
    }

    const user = new NewUser();
    user.username = username;
    user.password = password;
    user.email = email;

    return this.userRepository.save(user);
  }

  async findAll() {
    return this.userRepository.find();
  }

  async findOne(id: string) {
    return this.userRepository.findOne({
      where: { id: id },
    });
  }

  async findByUsername(username: string) {
    return this.userRepository.findOne({
      where: { username },
    });
  }

  async update(id: string, updateUserDto: UpdateUserDto) {
    const { username, password, email } = updateUserDto;

    return this.userRepository.update(
      { id: id },
      { username, password, email },
    );
  }

  async remove(id: string) {
    return this.userRepository.delete({
      id: id,
    });
  }
}
